import Storage from '@/common/Storage'
import { getUserInfo } from '../../api/user'

const state = {
  userInfo: false,
  addressInfo: null
}

const mutations = {
  SET_USER_ADDRESS (state, value) {
    state.addressInfo = value
    Storage.set('userAddressInfo', value, 1)
  },
  SET_USER_INFO (state, value) {
    console.log('SET_USER_INFO is data', value)
    state.userInfo = value
    Storage.set('userInfo', value)
    // 要覆盖，不然有时候user_id删不掉
    if (value && value.id) {
      Storage.set('user_id', value.id, 1)
    } else {
      Storage.remove('user_id')
      Storage.remove('userInfo')
      Storage.remove('access_token')
    }
  }
}

const actions = {
  /**
   * 获取用户信息的同步版本
   * @param commit
   * @param conf
   * @returns {Promise<boolean|*>}
   */
  getUserInfo: async ({ commit }, conf = {}) => {
    try {
      const { stroage = 'local' } = conf
      let data
      if (stroage === 'local') {
        // 第一次是在内存里
        data = state.userInfo || Storage.get('userInfo')
        if (!data || typeof data !== 'object') throw Error('获取用户信息失败')
      } else {
        const userInfo = await getUserInfo().then(res => res.data).catch(err => {
          throw Error(err.msg)
        })
        commit('SET_USER_INFO', userInfo)
        data = userInfo
      }

      return data
    } catch (e) {
      return false
    }
  },
  setUserInfo: ({ commit }, data) => {
    commit('SET_USER_INFO', data)
  },
  setUserAddressInfo: ({ commit }, data) => {
    commit('SET_USER_ADDRESS', data)
  }
}

const getters = {
  getUserAddressInfo: (state) => () => {
    try {
      // 第一次是在内存里
      const data = state.addressInfo || Storage.get('userAddressInfo')
      if (!data || typeof data !== 'object') throw Error('获取用户信息失败')
      return data
    } catch (e) {
      return {}
    }
  },
  addressInfo: (state) => state.addressInfo || Storage.get('userAddressInfo'),
  userInfo: (state) => state.userInfo || Storage.get('userInfo'),
  getUserId: (state) => () => {
    const userInfo = state.userInfo || Storage.get('userInfo')
    if (userInfo && userInfo.hasOwnProperty('User_ID')) {
      return userInfo.User_ID
    }
    return 0
  },
  // 利用方法的方式去获取
  getUserInfo: (state) => () => {
    try {
      // 第一次是在内存里
      const data = state.userInfo || Storage.get('userInfo')
      if (!data || typeof data !== 'object') throw Error('获取用户信息失败')
      return data
    } catch (e) {
      return {}
    }
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
